package ltd.sshine.networkserver.service.impl;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import lombok.extern.slf4j.Slf4j;
import ltd.sshine.networkserver.service.ProxyService;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;
@Slf4j
@Service
public class ProxyServiceImpl implements ProxyService {
    @Override
    public void proxy(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest, String remoteHost, String remotePort) {
        InetSocketAddress remoteAddress = new InetSocketAddress(remoteHost,Integer.parseInt(remotePort));
        ChannelFuture connect = new Bootstrap()
                .group(new NioEventLoopGroup()).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        channel.pipeline().addLast(new HttpClientCodec());
                        channel.pipeline().addLast(new HttpObjectAggregator(65536));
                        channel.pipeline().addLast(new SimpleChannelInboundHandler<FullHttpResponse>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx0, FullHttpResponse msg) throws Exception {
                                // 处理响应
                                FullHttpResponse copy = msg.copy();
                                log.debug("代理请求成功");
                                ctx.channel().writeAndFlush(copy);
                            }

                            @Override
                            public void exceptionCaught(ChannelHandlerContext ctx0, Throwable cause) throws Exception {
                                // 处理异常
                                cause.printStackTrace();
                                ctx0.close();
                                ctx.close();
                            }
                        });

                    }
                })
                .connect(remoteAddress);
        connect.addListener((ChannelFutureListener) future -> {
            if (future.isSuccess()) {
                future.channel().writeAndFlush(fullHttpRequest.copy());
            } else {
                connect.channel().close();
                ctx.channel().close();
            }
        });
    }
}
